import os
import sys

from abc import ABC, abstractmethod

thisDir = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(os.path.join(thisDir, "..", "common"))

import EJOConst
import EJOConfig
from SessionManager import SessionManager

import logging
logger = logging.getLogger(__name__)

class EJOAmountWithCurrencyProvider(ABC):
    @abstractmethod
    def Get(self):
        # Result: amount, date, currency
        pass

def EJOGetExchangeRate(date, currency):
    cny = 1
    if currency == cny:
        return 100.0

    sql = "select " + \
         "exchangerate.Rate as rate" + \
         " from " + \
         "exchangerate" + \
         " where " + \
         "exchangerate.Datetime = '" + date + "'" + \
         " and " + \
         "exchangerate.Currency = " + str(currency)

    rate = None
    db = SessionManager().GetProperty(EJOConst.SESSION_PROPERTY_DB)
    for row in db.Execute(sql):
        rate = row[0]
        # There should be only one record, so return directly
        break

    if rate is None:
        logger.warning(f"Exchange rate not found for ({date}, {currency})")
        return 0

    return rate

def EJOSumByCurrency(amountWithCurrencyProvider):
    finalAmount = 0.0
    for amount, date, currency in amountWithCurrencyProvider:
        rate = EJOGetExchangeRate(date, currency)
        finalAmount += (rate * amount / 100.0)
    return finalAmount
